<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :span="6">
                <a-form-item label="开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange1"
                    :style="{ width: '100%' }"
                    v-model="timeOn"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange2"
                    :style="{ width: '100%' }"
                    v-model="timeEnd"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="违章单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    allowClear
                    showSearch
                    style="width: 100%"
                    tree-node-filter-prop="title"
                    v-model="selectedKeys"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="onChangeData"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择部门"
                    :title="selectedKeys"/>
                </a-form-item>
              </a-col>
              <a-col :span="3" class="search-buttons">
                <a-button type="primary" @click="handleClick" v-if="hasPerm('hdv_qhse_unitViolationWarning')">查询</a-button>
              </a-col>
              <a-col :span="2" class="search-buttons">
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="48">
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card>
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.organizationId"
          :rowSelection="null"
          bordered
        >
          <span slot="action" slot-scope="text, record" style="display: flex;">
            <a-button size="small" style="color:#389e0d;background-color: #f6ffed;border-color: #b7eb8f;">
              <a @click="$refs.violationDetail.edit(record)">
                <a-icon type="file-text" />
                查看详情
              </a>
            </a-button>
          </span>
        </s-table>
        <violationDetail ref="violationDetail" @ok="handleOk"/>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import { STable, XCard, XDown } from '@/components'
import { Empty } from 'ant-design-vue'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
import { getDepartmentEarlyViolationWarning } from '@/api/modular/system/QHSEWarning'
import moment from 'moment'
import violationDetail from './violationDetail'
import { mapGetters } from 'vuex'
export default {
  components: {
    XDown,
    XCard,
    STable,
    violationDetail
  },
  data() {
    // 获取当前日期时间
    const currentDate = moment(new Date())
    // 计算开始时间，如果一个月以前是上一年，则从当前年份的一月一号开始
    const startOfThisYear = moment(currentDate).startOf('year')
    const startOfMonthAgo = moment(currentDate).subtract(1, 'month')
    const startTime = startOfMonthAgo.isBefore(startOfThisYear) ? startOfThisYear : startOfMonthAgo
    // 设置结束时间，当前日期的23:59:59
    const endTime = moment(currentDate).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
    // 设置参数对象
    const queryParam = {
      timeOn: startTime.format('YYYY-MM-DD'),
      timeEnd: endTime,
      score: 3
    }
    const getParam = {
      timeOn: startTime.format('YYYY-MM-DD HH:mm:ss'),
      timeEnd: endTime
    }
    return {
      // 查询参数
      queryParam,
      getParam,
      timeEnd: moment(new Date(), 'YYYY-MM-DD'),
      timeOn: startTime,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 表头
      columns: [
        {
          title: '开始时间',
          dataIndex: 'timeOn',
          customRender: (text, record) => {
            if (record.timeOn) {
              const dateParts = record.timeOn.split('T')[0].split('-')
              return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`
            }
            return ''
          }
        },
        {
          title: '结束时间',
          dataIndex: 'timeEnd',
          customRender: (text, record) => {
            if (record.timeEnd) {
              const dateParts = record.timeEnd.split('T')[0].split('-')
              return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`
            }
            return ''
          }
        },
        {
          title: '单位',
          dataIndex: 'organizationName'
        },
        {
          title: '重大违章',
          dataIndex: 'majorViolationsNumber',
          customRender: function(text) {
              return <span style={{ fontWeight: 'bold', color: 'red' }}>{text}</span>
          }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return getDepartmentEarlyViolationWarning(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      selectedKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      QHSEOrganizationTree: [],
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      secondOraName: {
          id: ''
        }
    }
  },
  computed: {
      ...mapGetters(['userInfo'])
      },
  created() {
    this.getQHSEOrganizationTree()
    this.columns.push({
      title: '操作',
      width: '200px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    })
  },
  mounted() {
    const selectKey1 = this.$route.query.organizationName
    this.getParam.organizationName = selectKey1
    this.selectedKeys = selectKey1
    const selectKey2 = this.$route.query.timeOn
    this.timeOn = selectKey2 ? moment(selectKey2) : this.timeOn
    this.getParam.timeOn = selectKey2 === undefined ? this.queryParam.timeOn : selectKey2
    const selectKey3 = this.$route.query.timeEnd
    this.getParam.timeEnd = selectKey3 === undefined ? this.queryParam.timeEnd : selectKey3
    this.timeEnd = selectKey3 ? moment(selectKey3) : this.timeEnd
    const selectKey4 = this.$route.query.organizationId
    this.getParam.organizationId = selectKey4
    this.queryParam = { ...this.getParam }
    if (this.selectedKeys) {
      this.handleClick()
    }
  },
  methods: {
    handleClick() {
      if (
       (this.timeOn && this.timeOn.year && this.timeOn.month && this.timeOn.day) &&
       (this.timeEnd && this.timeEnd.year && this.timeEnd.month && this.timeEnd.day) &&
       this.selectedKeys && this.selectedKeys.length > 0) {
        // console.log('this.queryParam', this.queryParam)
        this.$refs.table.refresh(true)
       } else {
       // 提示用户需要填写完整的时间信息
       this.$message.warning('请填写完整的信息')
     }
    },
    onChange1(date, dateString) {
    //   console.log(dateString, date)
      if (this.queryParam.timeEnd && dateString) {
        if (dateString > this.queryParam.timeEnd) {
          this.$message.error('开始时间不能晚于结束时间')
          this.timeEnd = moment(new Date(), 'YYYY-MM-DD')
          this.timeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.timeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.timeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.timeOn = dateString
        }
      } else {
        this.queryParam.timeOn = dateString
      }
    },
    onChange2(date, dateString) {
      if (this.queryParam.timeOn && dateString) {
        if (this.queryParam.timeOn > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.timeEnd = moment(new Date(), 'YYYY-MM-DD')
          this.timeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.timeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.timeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.timeEnd = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.timeEnd = dateString + 'T' + moment().format('23:59:59')
      }
    },
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
      this.treeLoading = false
      if (!res.success) {
          return
      }
      this.QHSEOrganizationTree = res.data
      if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
     })
    },
    onChangeData(value, label, extra) {
      // console.log(extra)
      if (extra.triggerNode === undefined) {
        this.queryParam.organizationName = ''
        this.queryParam.organizationId = ''
      } else {
        this.queryParam.organizationName = extra.triggerNode._props.title
        this.queryParam.organizationId = extra.triggerNode._props.value
        this.selectedKeys = extra.triggerNode._props.title
      }
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    reset() {
      this.queryParam = {
        timeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        timeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
      }
      this.timeEnd = moment(new Date(), 'YYYY-MM-DD')
      this.timeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
      this.selectedKeys = []
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/.ant-table-tbody tr:nth-child(2n) {
    background-color:#FAFAFA;
  }
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
}

</style>
